import { useEffect, useRef, useState } from 'react'

export default function useCountDown (initCount = 10, callback = () => {}) {
//   const timerID = useRef<{id:number }>(null)
  const timerID = useRef({ id: -1 }) // setInterval的返回值不会小于0

  const [count, setCount] = useState(initCount)
  const start = () => {
    setCount(initCount)
    timerID.current!.id = window.setInterval(() => {
      setCount((count) => count - 1)
    }, 1000)
  }
  useEffect(() => {
    return () => {
      console.log('------------------')
      window.clearInterval(timerID.current!.id)
    }
  }, [])
  useEffect(() => {
    console.log(count, timerID.current)
    if (count === 0) {
      window.clearInterval(timerID.current!.id)
      callback()
    }
  }, [count])
  return { count, start }
}
